import os
from typing import Any, Dict
import toml  # 需要安装 tomli 库（Python 3.11+ 内置 tomllib）

from common.log import logger

# 配置可用的默认设置
# device可选参数为：cuda:0、cpu
available_setting = {
    # 身份提示词
    "sys_prompt": "",
    "model": {},
    "project_path": ""  # 项目路径，可以不用填写
}

default_config_file = "default_config.toml"  # 修改文件扩展名


def ensure_file_exists(filepath: str, default_content: Dict[str, Any]):
    """确保文件存在，如果不存在则创建并写入默认内容"""
    if not os.path.exists(filepath):
        os.makedirs(os.path.dirname(filepath), exist_ok=True)
        with open(filepath, "w", encoding="utf-8") as f:
            toml.dump(default_content, f)  # 使用 toml 替代 json
        logger.info(f"Created default configuration file at {filepath}.")


def get_project_path():
    # 保持不变
    current_dir = os.path.dirname(os.path.abspath(__file__))
    return os.path.dirname(current_dir)


class Config(dict):
    def __init__(self, file_name: str = "config/config.toml", encoding: str = "utf-8"):  # 修改默认文件名
        super().__init__()
        self.encoding = encoding
        self.file_name = file_name
        self.default_file = self.get_config_file_path(default_config_file)

        # 确保默认配置文件存在
        ensure_file_exists(self.default_file, available_setting)
        self.load_config(self.get_config_file_path(file_name))
        if not self["project_path"]:
            self["project_path"] = get_project_path()

    def load_config(self, filename: str):
        """加载 TOML 配置文件"""
        if not os.path.exists(filename):
            logger.warning(f"{filename} not found. Loading default configuration.")
            filename = self.default_file

        try:
            with open(filename, 'r', encoding=self.encoding) as f:
                config_data = toml.load(f)  # 使用 toml 加载
                for k, v in config_data.items():
                    self[k] = v
        except FileNotFoundError:
            raise FileNotFoundError(f"Configuration file '{filename}' not found.")
        except toml.TomlDecodeError as e:  # 修改异常类型
            raise ValueError(f"Error parsing TOML file '{filename}': {e}")

    @staticmethod
    def get_config_file_path(file_name: str) -> str:
        # 保持不变
        common_dir = os.path.dirname(os.path.abspath(__file__))
        project_root = os.path.dirname(common_dir)
        return os.path.join(project_root, file_name)

    # 以下 __getitem__ 和 __setitem__ 保持不变
    def __getitem__(self, key: str) -> Any:
        if key not in available_setting:
            raise KeyError(f"Key {key} not in available_setting")
        return super().get(key, available_setting[key])

    def __setitem__(self, key: str, value: Any):
        if key not in available_setting:
            raise KeyError(f"Key {key} not in available_setting")
        super().__setitem__(key, value)


config = Config()


def conf() -> Config:
    """获取全局配置实例"""
    return config


if __name__ == '__main__':
    if config["model"]:
        print(config["model"])
    else:
        print("vad_path not found")
